package com.casstime.ec.cloud.meeting.web.util;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

public class RedisCache {
	
	private static RedisTemplate<String, Object> redisTemplate;

	private static Logger logger = LoggerFactory.getLogger(RedisCache.class);
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void setRedisTemplate(RedisTemplate redisTemplate) {
		RedisCache.redisTemplate = redisTemplate;
	}
	
	public static String getStringValue(String key){
		String value = "";
		try {
			Object obj = getValue(key);
			if(null!=obj){
				value = obj.toString();
			}
		} catch (Exception e) {
			logger.error("获取Redis缓存失败key-{}",key,e);
			return value;
		}
		return value;
	}
	
	public static Object getValue(String key){
		Object obj = null;
		try {
			ValueOperations<String, Object> oper = redisTemplate.opsForValue();
			obj = oper.get(key);
		}catch(Exception e){
			logger.error("获取Redis缓存失败key-{}",key,e);
			return null;
		}
		return obj;
	}
	
	public static Object getListValue(String key){
		Object obj = null;
		try {
			ValueOperations<String, Object> oper = redisTemplate.opsForValue();
			obj = oper.get(key);
		}catch(Exception e){
			logger.error("获取Redis缓存失败key-{}",key,e);
			return null;
		}
		return obj;
	}
	/**
	 * 新增缓存
	 * @author JumZeng
	 * @since 2017年2月24日
	 * @param key
	 * @param val
	 * @param seconds	过期时间 ：秒
	 */
	public static void setValue(String key,Object val,int seconds){
		try{
			ValueOperations<String, Object> oper = redisTemplate.opsForValue();
			oper.set(key, val);
			redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
		}catch(Exception e){
			logger.error("写入Redis缓存失败key-->{},val-->{}",key,val,e);
		}
	}
}
